package edu.mis.modules.orderproduct;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.jfinal.core.Controller;

import edu.mis.model.Customer;
import edu.mis.model.Member;
import edu.mis.model.Orderproduct;
import edu.mis.model.Orderproductitem;
import edu.mis.modules.customer.CustomerService;
import edu.mis.modules.member.MemberService;
import edu.mis.modules.orderproductitem.OrderproductitemService;
import edu.mis.modules.pay.PayService;
import edu.mis.modules.product.ProductService;
import edu.mis.modules.user.UserService;

public class OrderproductController extends Controller{
	
	static UserService userService = new UserService();
    static OrderproductService orderproductService = new OrderproductService();
    static OrderproductitemService orderproductitemService = new OrderproductitemService();
	static ProductService productService = new ProductService();
    static CustomerService customerService = new CustomerService();
    static PayService payService = new PayService();
    static MemberService memberService =  new MemberService();
    
	public void index() {
		if(userService.findUserWithRole().equals(1)) {
			render("orderproduct.html");
		}else if(userService.findUserWithRole().equals(2)) {
			render("cashierOrderproduct.html");
		}else{
			render("noAllAuthority.html");	 
		}
		
	}
	
	public void list(){
		setAttr("data", orderproductService.findAllRecordWithName());
		renderJson();  
	}
	
	/**
	 * 添加订单视图
	 */
	public void add() {
		//render("add.html");  //（默认对应add.html，否则需显性指定，如render("addRole.html")
		setAttr("orderproductNumber", orderproductService.ramdomOrderproductNumber());
		setAttr("customer",customerService.findAllCustomer());//添加订单前得到所有客户
		setAttr("product",productService.findAllProduct());
		setAttr("login",userService.findLoginUser());
		render("addfirst.html");
	}
	
	/**
	 * 添加订单
	 */
	static int customerId;
	static int i=0;
	static Map<Integer,Orderproductitem> orderproductitems = new HashMap<Integer,Orderproductitem>();
	static Orderproduct orderproduct = new Orderproduct();
	
	public void register(){
		Orderproduct orderproductOther = getModel(Orderproduct.class);
		Orderproductitem orderproductitem = getModel(Orderproductitem.class);
		int control = getParaToInt("control");
		//control=0表示添加产品
		if(control==0) {
			i++;
			System.out.println("第"+i+"次添加项目");
			//第一次添加产品
			if(i==1) {
				
				if(orderproductOther.getCustomerId()!=-1) {
					customerId = orderproductOther.getCustomerId();
					orderproduct.setOrderproductNumber(orderproductOther.getOrderproductNumber());
					orderproduct.setUserId(userService.findLoginUser().getUserId());
					orderproduct.setCustomerId(customerId);
					
					//判断是否存在空值
					if(orderproductitem.getProductId()!=-1) {
						if(orderproductitem.getAmount()!=null || orderproductitem.getAmount()!=0) {
							orderproductitem.setOrderproductNumber(orderproduct.getOrderproductNumber());
							orderproductitem.setProductPrice(productService.findProductByProductId(orderproductitem.getProductId()).getProductPrice());
							orderproductitem.setSum(orderproductitem.getAmount()*orderproductitem.getProductPrice());
							orderproductitems.put(i, orderproductitem);
							
							setAttr("result", true); 
						    setAttr("msg", "添加产品成功!");
						}else {
							i--;
							setAttr("result", false); 
						    setAttr("msg", "添加产品失败，数量为零或空!");	
						}
						
					}else {
						i--;
						setAttr("result", false); 
					    setAttr("msg", "添加产品失败，产品为空!");	
					}

			    }else {
				    i--;
				    setAttr("result", false); 
				    setAttr("msg", "添加产品失败，客户为空!");	
			    }
				
			}
			
			if(i>1) {
				//判定是否同一个客户
				if(customerId == orderproductOther.getCustomerId()) {
					//判断是否存在空值
					if(orderproductitem.getProductId()!=-1) {
						if(orderproductitem.getAmount()!=null || orderproductitem.getAmount()!=0) {
							orderproductitem.setOrderproductNumber(orderproduct.getOrderproductNumber());
							orderproductitem.setProductPrice(productService.findProductByProductId(orderproductitem.getProductId()).getProductPrice());
							orderproductitem.setSum(orderproductitem.getAmount()*orderproductitem.getProductPrice());
							orderproductitems.put(i, orderproductitem);
							
							setAttr("result", true); 
						    setAttr("msg", "添加产品成功!");
						}else {
							i--;
							setAttr("result", false); 
						    setAttr("msg", "添加产品失败，数量为零或空!");	
						}
						
					}else {
						i--;
						setAttr("result", false); 
					    setAttr("msg", "添加产品失败，产品为空!");	
					}
					
				}else {
					i--;
					setAttr("result", true); 
					setAttr("msg", "添加产品失败，不是同一个客户!");	
				}
				
			}
				
		}
		
		
		if(control==1) {
			//第一次不添加，直接提交
			if(i==0) {
				
				if(orderproductOther.getCustomerId()!=-1) {
					customerId = orderproductOther.getCustomerId();
					orderproduct.setOrderproductNumber(orderproductOther.getOrderproductNumber());
					orderproduct.setUserId(userService.findLoginUser().getUserId());
					orderproduct.setCustomerId(customerId);
					
					//判断是否存在空值
					if(orderproductitem.getProductId()!=-1) {
						
						if(orderproductitem.getAmount()!=null || orderproductitem.getAmount()!=0) {
							
							orderproductitem.setOrderproductNumber(orderproduct.getOrderproductNumber());
							orderproductitem.setProductPrice(productService.findProductByProductId(orderproductitem.getProductId()).getProductPrice());
							orderproductitem.setSum(orderproductitem.getAmount()*orderproductitem.getProductPrice());
							orderproductitems.put(i, orderproductitem);
							
							setAttr("result", true); 
						    setAttr("msg", "添加产品成功!");
						}else {
							
							i--;
							setAttr("result", false); 
						    setAttr("msg", "添加产品失败，数量为零或空!");	
						}
						
					}else {
						
						i--;
						setAttr("result", false); 
					    setAttr("msg", "添加产品失败，产品为空!");	
					}

			    }else {
				    i--;
				    setAttr("result", false); 
				    setAttr("msg", "添加产品失败，客户为空!");	
			    }	
				
			}
			
			//最后提交
			if(i>0) {
				
				//判定是否同一个客户
				if(customerId == orderproductOther.getCustomerId()) {
					//判断是否存在空值
					if(orderproductitem.getProductId()!=-1) {
						if(orderproductitem.getAmount()!=null || orderproductitem.getAmount()!=0) {
							i++;
							orderproductitem.setOrderproductNumber(orderproduct.getOrderproductNumber());
							orderproductitem.setProductPrice(productService.findProductByProductId(orderproductitem.getProductId()).getProductPrice());
							orderproductitem.setSum(orderproductitem.getAmount()*orderproductitem.getProductPrice());
							orderproductitems.put(i, orderproductitem);
							
							setAttr("result", true); 
						    setAttr("msg", "添加产品成功!");
						}
					}
					
				}else {
					i--;
					setAttr("result", true); 
					setAttr("msg", "添加产品失败，不是同一个客户!");	
				}	
				
			}
			
			orderproduct.setTime(new Date());
			Integer total=0;
			for(Map.Entry<Integer, Orderproductitem> entry : orderproductitems.entrySet()) {
				total += entry.getValue().getSum();
			}
			
			orderproduct.setTotal(total);
			orderproduct.setPayId(-1);
			orderproduct.setPayment(0);
			if(orderproductService.register(orderproduct)) {
				for(Map.Entry<Integer, Orderproductitem> entry : orderproductitems.entrySet()) {
					entry.getValue().save();
				}
				
				System.out.println("i重置前值为"+i);
				customerId=-1;
				i=0;
				System.out.println("重置的i值为"+i);
				orderproductitems = new HashMap<Integer,Orderproductitem>();
				orderproduct = new Orderproduct();
			}
			
			
		}
		
		if(control==2) {
			System.out.println("i重置前值为"+i);
			customerId=-1;
			i=0;
			System.out.println("重置的i值为"+i);
			orderproductitems = new HashMap<Integer,Orderproductitem>();
			orderproduct = new Orderproduct();
		}
		
		renderJson(); 
	}
	
	/**
	 * 修改订单视图
	 */
	public void edit() {
		setAttr("orderproduct", orderproductService.findOrderproductById(getParaToInt("orderproductId")));  
		setAttr("customer",customerService.findAllCustomer());
		setAttr("product",productService.findAllProduct());
	}
	
	
	/**
	 * 支付视图
	 */
	public void auth() {
		setAttr("orderproduct", orderproductService.findOrderproductById(getParaToInt("orderproductId")));  
	}
	
	/**
	 * 支付
	 */
	public void authorize(){
		
		int orderproductId = this.getParaToInt("orderproductId");   
		//int payId = this.getParaToInt("payId");
		
		System.out.println("orderproductId"+orderproductId);
		
		
		Orderproduct orderproduct = orderproductService.findOrderproductById(orderproductId);
		Customer customer = customerService.findCustomerByCustomerId(orderproduct.getCustomerId());
		Member member = memberService.findMemberByCustomerNumber(customer.getCustomerNumber());
		
		if(orderproduct.getPayId()==-1) {
			
			int payment = orderproduct.getTotal();
			int memberPaymemt = (int)(payment*0.95);
			
			//会员支付(1，代表会员）
			if(customer.getVip()==1) {
				orderproduct.setPayment(memberPaymemt);
				orderproduct.setPayId(1);
				if(payment>200) {
					int memberScore = (payment/200)*10;
					member.setMemberScore(member.getMemberScore()+memberScore);
				}
				if(orderproductService.updateOrderproduct(orderproduct)==true && memberService.updateMember(member)==true) {
					setAttr("result", true);
					setAttr("msg", "订单支付成功!");
				}else {
					setAttr("result", false);
					setAttr("msg", "订单支付失败,系统错误!");
					
				}
			//普通支付	
			}else {
				orderproduct.setPayment(payment);
				orderproduct.setPayId(1);
				if(orderproductService.updateOrderproduct(orderproduct)) {
					setAttr("result", true);
					setAttr("msg", "订单支付成功!");
				}else {
					setAttr("result", false);
					setAttr("msg", "订单支付失败,系统错误!");
				}
			}
			
		}else {
			setAttr("result", false);
			setAttr("msg", "订单支付,请不要重复支付!");
		}
		renderJson();
	}
	
	/**
	 * 删除订单
	 * 
	 */
	public void delete() {
		int orderproductId = getParaToInt("orderproductId");
		int orderproductNumber = orderproductService.findOrderproductById(orderproductId).getOrderproductNumber();
		System.out.println(orderproductNumber);
		
		if(orderproductitemService.deleteOrderproductitemByOrderproductNumber(orderproductNumber)) {
			setAttr("result", false);
			setAttr("msg", "删除订单失败!");
		}else {
			if(orderproductService.deleteOrderproductByOrderproductId(orderproductId)){
				setAttr("result", true);
				setAttr("msg", "删除订单成功!");
			}else{
				setAttr("result", false);
				setAttr("msg", "删除订单失败!");
			}
		}
		renderJson();
	}
}
